package com.fiidee.blog.controller.common.avatar;

import com.alibaba.fastjson.JSONObject;
import com.fiidee.blog.util.Uploader;
import com.fiidee.blog.util.ReturnJsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 瑱彬 on 2015/6/2.
 */
@Controller
@RequestMapping("/avatar")
public class UploadAvatar {
    @RequestMapping(value = "/upload")
    @ResponseBody
    public JSONObject upload(HttpServletRequest request, HttpServletResponse response){
        try {
            //System.out.println("upfile----->"+new String(upfile.getBytes()));
            Uploader up = new Uploader(request);
            up.setSavePath("upload");
            String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
            up.setAllowFiles(fileType);
            up.setMaxSize(510); //单位KB
            up.uploadAnonymous(request);

            String callback = request.getParameter("callback");

            String resultstr = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
            System.out.println(resultstr);
            JSONObject result = ReturnJsonUtil.successMsg(up.getUrl());
            result.put("code",200);
            if( callback == null ){
                return result;
            }else{
                result.put("callback","<script>"+ callback +"(" + result + ")</script>");
                return  result;
            }
        } catch (Exception e) {
            JSONObject result = ReturnJsonUtil.errorMsg(e.getMessage());
            return result;
        }
    }
}
